package com.hbnu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.bean.User;
import com.hbnu.mapper.SysUserMapper;
import com.hbnu.req.UserLoginReq;
import com.hbnu.req.UserSaveReq;
import com.hbnu.resp.UserLoginResp;
import com.hbnu.service.SysUserService;
import com.hbnu.utils.CopyUtil;
import com.hbnu.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @Auther: hjx
 * @Date: 2023/6/14 08:05
 * @Description:
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, User> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SnowFlake snowFlake;


    @Override
    public void register(UserSaveReq req) {
        User user = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            User userDB = selectByLoginName(req.getLoginName());
            //如果为空，说明该用户名还没有被注册过
            if(ObjectUtils.isEmpty(userDB)){
                //调用雪花算法加密
                user.setId(snowFlake.nextId());
                //调用sysUserMapper继承自BaseMapper中的insert方法
                sysUserMapper.insert(user);
            }
        }
    }

    @Override
    public UserLoginResp login(UserLoginReq req) {
        /**
         * 1.先去拿登陆的这个用户名去数据库进行对比，分为存在和不存在的情况
         * */
        User userDB = selectByLoginName(req.getLoginName());
        System.out.println(userDB);
        if(ObjectUtils.isEmpty(userDB)){
            //用户名不存在
                return null;
        }else{
            //用户名存在的情况
            UserLoginResp userLoginResp = CopyUtil.copy(userDB, UserLoginResp.class);
            return userLoginResp;


        }
    }

    //查询loginName是否被注册
    public User selectByLoginName(String loginName) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", loginName);
        List<User> userList = sysUserMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        } else {
            return userList.get(0);
        }
    }
}

